using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using MediatR;
using B.S.ReportEvent.ApiNew.Commands.Instance;
using B.S.ReportEvent.ApiNew.Dtos.ResponseDto;
using B.S.ReportEvent.ErrorCode;
using B.S.ReportEvent.ErrorCode.ErrorCodes;
using B.S.ReportEvent.Infrastructure.Interfaces;

namespace B.S.ReportEvent.ApiNew.CommandHandlers.Instance
{
    /// <summary>
    /// 查询当前用户待办实例命令处理器
    /// </summary>
    public class GetMyTodoInstancesCommandHandler : IRequestHandler<GetMyTodoInstancesCommand, ApiResult<GetMyTodoInstancesResponseDto>>
    {
        private readonly IWfInstancesRepository _repository;
        private readonly ILogger<GetMyTodoInstancesCommandHandler> _logger;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="logger"></param>
        public GetMyTodoInstancesCommandHandler(IWfInstancesRepository repository, ILogger<GetMyTodoInstancesCommandHandler> logger)
        {
            _repository = repository;
            _logger = logger;
        }
        
        /// <summary>
        /// 处理查询当前用户待办实例命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<GetMyTodoInstancesResponseDto>> Handle(GetMyTodoInstancesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var instances =  _repository.GetAll().Where(x=>x.CurrentOperatorId==request.UserId&& x.FlowStatus==0).ToList();
                
                return Task.FromResult(ApiResult<GetMyTodoInstancesResponseDto>.Success(new GetMyTodoInstancesResponseDto()
                {
                    Items = instances
                }, StatusCodeEnum.Ok));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "查询当前用户待办实例失败");
                return Task.FromResult(ApiResult<GetMyTodoInstancesResponseDto>.Fail("查询当前用户待办实例失败", StatusCodeEnum.Fail));
            }
        }
    }
}